package com.baidu.aihsp.algoservice.service;

import com.baidu.aihsp.algoservice.entity.Algo;
import com.baidu.aihsp.algoservice.repository.AlgoRepository;
import com.baidu.aihsp.algoservice.util.UpdateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

/**
 * @author wenchang
 * @create 2020-08-25-12:02
 */
@Service
public class AlgoService {

    @Autowired
    AlgoRepository algoRepository;

    public Algo save(Algo algo){
        Algo byId = algoRepository.findById(algo.getId())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND,"ALGO_INFO_NOT_FOUND"));
        UpdateUtil.copyNullProperties(algo,byId);
        return algoRepository.save(byId);
    }

    public Page<Algo> getList(Pageable pageable){
        return algoRepository.findAll(pageable);
    }

    public Algo getOne(Long algoId){
        return algoRepository.findById(algoId)
                .orElseThrow(() ->new  ResponseStatusException(HttpStatus.NOT_FOUND,"ALGO_INFO_NOT_FOUND"));
    }

    public void deleteById(Long algoId){
        algoRepository.deleteById(algoId);
    }

    public Algo add(Algo algo){
        return algoRepository.save(algo);
    }
}
